package x.ovo.wechat.bot.plugin;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.io.IoUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.json.JSONArray;
import org.dromara.hutool.json.JSONUtil;
import x.ovo.wechat.bot.core.event.EventListener;
import x.ovo.wechat.bot.core.event.MessageEvent;
import x.ovo.wechat.bot.core.message.TextMessage;
import x.ovo.wechat.bot.core.plugin.Plugin;

import java.util.Objects;
import java.util.Random;

@Slf4j(topic = "KFC")
public class KfcListener extends EventListener<MessageEvent<TextMessage>, TextMessage> {

    private static JSONArray DOCS;
    private static final Random RANDOM = new Random();

    static {
        try {
            DOCS = JSONUtil.parseArray(IoUtil.read(IoUtil.toUtf8Reader(KfcListener.class.getClassLoader().getResourceAsStream("docs.json"))));
        } catch (Exception ee) {
            log.error("读取文档失败", ee);
        }
    }

    public KfcListener(Plugin plugin) {
        super(plugin);
    }

    @Override
    public boolean support(@NonNull MessageEvent<TextMessage> textMessageMessageEvent, TextMessage message) {
        String content = message.getContent().toLowerCase();
        return content.contains("kfc") || content.contains("肯德基") || content.contains("v我50") || content.contains("疯狂星期四");
    }

    @Override
    public boolean onEvent(@NonNull MessageEvent<TextMessage> textMessageMessageEvent, TextMessage message) {
        try {
            String s = new KfcRequest().execute();
            if (StrUtil.isNotBlank(s) || Objects.nonNull(DOCS)) {
                message.getFrom().sendMessage(StrUtil.defaultIfBlank(s, DOCS.getStr(RANDOM.nextInt(DOCS.size()))));
            }
        } catch (Exception e) {
            if (Objects.nonNull(DOCS)) {
                message.getFrom().sendMessage(DOCS.getStr(RANDOM.nextInt(DOCS.size())));
            }
        }
        return true;
    }

    @Override
    public boolean executeNext() {
        return false;
    }
}
